<?php 
namespace Home\Controller;
use Think\Controller;

class UserController extends Controller{
	
	public function login(){
		if (!$_POST) {
			$this->display();
		}else{
			$user = D('user')->where('name="'.I('post.name').'"')->find();
			if( $user['password'] == $_POST['password'] ) {
				cookie('uid',$user['user_id']);
				cookie('username',$user['name']);
				cookie('email',$user['email']);
				cookie('nick',$user['nick']);
				$this->redirect('home/index/index');
			}else{
				echo "密码不对";
			}
		}		
	}

	public function register(){
		if(!$_POST){
			$this->display();
		}else{
			
			if(($_POST['name']=="")||($_POST['password']=="")||($_POST['nick']=="")||($_POST['email']=="")){
				echo "每一个都不能为空，写一个意思一下";
				exit();
			}
			
			if($this->checkyzm(I('post.yzm'))){
				$UserModel = D('user');
				$_POST['lastlogin']=time();
				$UserModel -> add($_POST);
				print_r($_POST);
				$this->redirect('home/index/index');	
			}else{
				echo "验证码错了，重来吧";
			}
		}
	}

	//退出清空cookie
	public function logout(){
		cookie('username',null);
		$this->redirect('/');
	}


	public function yzm(){  //验证码
		$Verify = new \Think\Verify();
		$Verify->imageW = 150; //设置验证码图片的宽度
		$Verify->imageH = 50;  //设置验证码图片的高度
		$Verify->fontSize = 15; //设置字体大小
		$Verify->length = 4;   //设置验证码多少个字
		$Verify->useNoise = false; //背景干扰是否存在
		$Verify->entry();
	}

	public function checkyzm($yzm){
		$Verify = new \Think\Verify();
		if($Verify->check($yzm)){
		return ture;
		}else{
		return false;
		}
	}


	public function CheckUsername(){
		if(!IS_AJAX){
			echo "页面不存在";
		}else{
			$usermodel = D('User');

			$all = $usermodel->where('user_id>0')->select();

			$username = array();

			foreach ($all as $key => $value) {
				//这个中括号很重要
				$username[] = $value['name'];
			}

			$u = $_POST['username'];

			$data = in_array($u, $username) ? 1 : 0;

			$this->ajaxReturn($data,'json');

			
		}
	}

	public function CheckEmail(){
		if(!IS_AJAX){

			echo "页面不存在";

		}else{

			$usermodel = D('User');

			$all = $usermodel->where('user_id>0')->select();

			$email = array();

			foreach ($all as $key => $value) {
				//这个中括号很重要
				$email[] = $value['email'];
			}

			$u = $_POST['email'];

			$data = in_array($u, $email) ? 1 : 0;

			$this->ajaxReturn($data,'json');						
		}
	}

}



?>